import store from "./store";
//导入路由
import router from "./router";
// D导入进度条
import nprogress from "nprogress";
// 导入进度条样式
import 'nprogress/nprogress.css'
// 准备白名单
const whileList = ['/login', '/404']
router.beforeEach(async (to, from, next) => {
    // to and from are both route objects. must call `next`.
    nprogress.start()
    if (store.getters.token) {
        if (to.path === '/login') {
            next('/')
        } else {
            // 如果有token,并且不是到登录页,那就发送请求获得用户数据
            // 再判断是不是已经有用户信息了
            // console.log(store.getters.userInfo.userId)
            if (!store.getters.name) {
                let res = await store.dispatch('user/getUserInfo')
                // 登录成功后获取用户的访问权限
                let routes = await store.dispatch('permission/getRoutes', res.roles.menus)
                // 解决在动态路由页面刷新的时候找不到页面的问题的第一步
                routes.push({ path: '*', redirect: '/404', hidden: true })
                // 拿到返回值，添加到路由里面去
                router.addRoutes(routes)
                // 用next()会出现刷新丢失页面的情况，所以要用next(to.path)第二步
                next(to.path)
            }
            next()
        }
    }
    else {
        if (whileList.includes(to.path)) {
            next()
        }
        else { next('/login') }
    }
})

router.afterEach((to, from) => {
    // to and from are both route objects.
    nprogress.done()
})

